<template>
  <div>
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt">
        <template slot="table-action">
          <el-button type="info" @click="addList">加入清单</el-button>
          <el-badge :value="waitingCount" class="contractapply-waiting">
            <el-button type="info" @click="openList">待签清单</el-button>
          </el-badge>
          <!-- <el-button type="info" @click="openList">待签清单({{waitingCount}})</el-button> -->
       </template>
        <template slot="table-tip">
            <em style="color:red;">【注：浅黄色底记录由于为非正式合作供应商尚不能签订合同，请确认是否转正！】</em>
        </template>
    </table-ext>
    <el-dialog :title="dl.title" :visible.sync="dl.sync" v-show="dl.show" @close="cancelDialog" :width="dl.width" :modal="dl.modal">
      <table-ext :columns="dl.columns" :config="dl.config" ref="dlTableExt">
        <template slot="table-action">
          <el-button type="info" @click="removeList">移除</el-button>
       </template>
      </table-ext>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取消</el-button>
        <el-button type="primary" @click.stop="createContract()">创建合同</el-button>
      </div>
      <el-dialog :title="editor.title" :visible.sync="editor.sync" append-to-body width="98%">
        <ContractEdit @createSuc="createSuc" :contract="contract" :purContractTypeList="purContractTypeList"></ContractEdit>
      </el-dialog>
    </el-dialog>
    <el-dialog :visible.sync="contentEditor.sync" :fullscreen="true" title="合同编辑" @close="contentEditorClose">
      <content-edit v-model="editId" @editContentSuc='editContentSuc' ref="contentEditor"></content-edit>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contentEditorClose">取 消</el-button>
        <el-button type="primary" @click="saveContent">确 定</el-button>
      </span>
    </el-dialog>    
  </div>

</template>
<script>
  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import TableIcon from '@/components/common/table-ext/table-icon';
  import ContractEdit from '@/components/contract/contractEdit';
  import ContentEdit from '@/components/contract/contractContentEdit';
  import qs from 'qs';
   export default {
    // 引入自定义表格组件
    components:{
      TableExt,
      ContractEdit,
      ContentEdit
    },
    data() {
      return {
        editId: '',
        editor: {
          title: '创建合同',
          sync: false
        },
        contract: {

        },
        contentEditor: {
          sync: false
        },
        purContractTypeList: [],
        waitingCount : 0,
        waitingList : [],
        dl: {
            modal: false,
            title: '清单列表',
            show: false,
            sync: true,
            width: '98%',
            config: {
              title: '待签清单',
              isNo: true,
              selection: true,
              crudMapping: {}
            },
            columns: [{
              label: 'id',
              key: 'id',
              hidden: true
            },{
              label: '单据编号',
              key: 'billNo',
              type: 'input'
            },{
              label: '公司',
              key: 'companyName',
              type: 'input'
            },{
              label: '采购组织',
              key: 'purOrgName'
            },{
              label: '物料',
              key: 'materialName'
            },{
              label: '供应商',
              key: 'vendorName'
            },{
              label: '数量',
              key: 'qty'
            },{
              label: '价格',
              key: 'price'
            },{
              label: '价格生效时间',
              key: 'priceStartDate'
            },{
              label: '价格失效时间',
              key: 'priceEndDate'
            }
            ]
        },
        config:{ // 页面共通配置
          title: '待签合同', //页面标题
          isPage: true, //是否分页
          isNo: true, //是否显示序号
          selection: true,//是否显示checkbox
          crudMapping:{ // CRUD方法
            query:{
              url: this.lib.config.host.contract + '/contractmgt/contract/apply/query'
            }
          }
        },
        // 查询表单配置
        searchForm:[{
          label: '采购组织编码', 
          key: 'purOrgCode', 
          type: 'input' 
        },{
          label: '供应商名称',
          key: 'vendorName',
          type: 'input'
        },{
          label: '单据号',
          key: 'billNo',
          type: 'input'
        },{
          label: '合同类型',
          key: 'contract',
          type: 'select',
          dict :[
              {lable: '询价',value: '1'},
              {lable: '招标',value: '2'},
              {lable: '竞价',value: '3'}
          ]
        },{
           label: '公司名称',
           key: 'cmpName',
           type: 'input' 
        },{
           label: '供应商编码',
           key: 'vendorName',
           type: 'input' 
        },{
           label: '发布人',
           key: 'publishName',
           type: 'input' 
        }
        ],
        // 表格列定义
        columns:[{
          label: 'id',
          key: 'id',
          hidden: true
        },{
          label: '物料',
          key: 'materialName',
          hidden: true
        },{
          label: '数量',
          key: 'qty',
          hidden: true
        },{
          label: '价格生效日期',
          key: 'priceStartDate',
          type: 'date',
          hidden: true
        },{
          label: '价格失效日期',
          key: 'billNo',
          type: 'date',
          hidden: true
        },{
          label: '公司名称',
          key: 'companyName'
        },{
          label: '采购组织名称',
          key: 'purOrgName'
        },{
          label: '单据号',
          key: 'billNo'
        },{
          label: '供应商编码',
          key: 'vendorCode'
        },{
          label: '供应商名称',
          key: 'vendorName'
        },{
          label: '来源类型',
          key: 'sourceType',
          render:(createElement, params)=>{ //动态渲染, 字典表示例
          let text = '';
          switch(params.row.sourceType){
            case 1:
            text = '询比价';break;
            case 2:
            text = '招投标';break;
            case 3:
            text = '竞价';break;
            
          }
            return createElement('el-tag',{props:{
                type: 'primary'
            }},text);
          }
        }
       ]
      }
    },
    methods: {
        addList(){
          let selectList = this.$refs.tableExt.multipleSelection;
          if(selectList.length<=0){
          this.showMsg('warning','没有选择记录');
          return;
          }
          let _this = this;
          this.$confirm('确认要加入该文件到待签清单吗?','提示',{
            confirmButtonText: '确认',
            cancleButtonText: '取消',
            type: 'warning'
          }).then(()=>{
            		let contractFlag = true;
                let mallCount = 0;
                selectList.forEach(bill=>{
                      if(bill.extendFlag==3){
                        mallCount++;
                      }   
                      if(bill.contractStatus !=null && bill.contractStatus != 0){
                        contractFlag = false;
                        return false;
                      }
                });
                //有已签清单
                if(!contractFlag){
                  _this.showMsg('warning','已签订合同');
                  return;
                }
                if(mallCount > 0 && mallCount != selectList.length){
                  _this.showMsg('warning', '不能同时加入商城集采与非商城集采数据，请检查！');
                  return;
                }
		
                let vendorArray = [];
                let purOrgArray = [];
                selectList.forEach(bill=>{
                  let flag = true;
                  for(let i = 0; i < vendorArray.length; i++){
                    if(vendorArray[i] == bill.vendorId && purOrgArray[i] == bill.purOrgId){
                      flag = false;
                    }
                    if(flag){
                    vendorArray.push(bill.vendorId);
                    purOrgArray.push(bill.purOrgId);
                    }
                  }
                });
                if(vendorArray.length > 1 || purOrgArray.length > 1){
                  _this.showMsg('warning','只能选择同一个供应商和同一个采购组织的数据');
                  return;
                }
                let listSels = _this.$refs.dlTableExt.tableData;
                mallCount = 0;
                listSels.forEach(item=>{
                  if(item.extendFlag==3){
                    mallCount ++;
                  }                  
                });
		
                if(mallCount > 0 && listSels.length > 0 && mallCount != listSels.length){
                  _this.showMsg('warning', '不能同时加入商城集采与非商城集采数据，请检查！');
                  return;
                }
		
                let selIdArray = [];
                let selCount = 0;
                selectList.forEach(bill=>{
                  let flag = true;
                  listSels.forEach(item=>{
                    if(bill.id == item.contractApplyId){
                      flag = false;
                    }
                  });
                  if(flag){
                    selIdArray.push(bill.id);
                    selCount++;
                  }
                });
		
		            let revendorFlag = true;
                if(listSels.length > 0){
                  let sel = listSels[0];
                  selectList.forEach(bill=>{
                    if(bill.vendorId != sel.vendorId || bill.purOrgId!=sel.purOrgId){
                      revendorFlag=false;
                      _this.showMsg('warning',"清单中的供应商:"+sel.vendorName+",采购组织:"+sel.purOrgName+";供应商:"+bill.vendorName+"采购组织:"+bill.purOrgName+"不能加入");
                      return false;
                    }
                  });
                }
                if(!revendorFlag){
                  return false;
                }
                if(selCount == 0) {
                  _this.showMsg('warning','加入'+selCount+'条单据!');
                  return;
                }else{
                 let idList = qs.stringify({idList: selIdArray},{arrayFormat: 'brackets'}) ;
                  _this.axios.post(_this.lib.config.host.contract+'/contractmgt/contract/apply/getItemList',idList).
                  then(res=>{
                    let data = res.data;
                    if(data.resultMap.itemList == null || data.resultMap.itemList.length <= 0){
                      _this.showMsg('warning','没有明细数据，不能加入');
                      return;
                    }
                    selCount = data.resultMap.count;
                    _this.showMsg('success','加入'+selCount+'条单据!');
                    data.resultMap.itemList.forEach(item=>{
                       _this.$refs.dlTableExt.tableData.push(item);
                    });
                    _this.waitingCount+=selIdArray.length;
                  }).catch(e=>{
                    _this.showMsg('error',e);
                  });
                }
          });
        },
        openList(){
          this.dl.show = true;
          this.dl.modal = true;
        },
        removeList(){
        //选择的明细
        let _this = this;
        let selections = this.$refs.dlTableExt.multipleSelection;
        //所有的明细
        let allRows = this.$refs.dlTableExt.tableData;
        if(selections.length <= 0){
          this.showMsg('warning','没有选择记录');
          return;
        }
        this.$confirm('移除时将根据主单移除，确定移除该单据吗?','提示').
        then(()=>{
          //选中的主单
          let selApplyIds = selections.map(n=>{
            return n.contractApplyId;
          });	
          selApplyIds = Array.from(new Set(selApplyIds));
          allRows.forEach((n)=>{
            //如果明细的主单在选中的主单中，放入删除的数组中
            if(selApplyIds.includes(n.contractApplyId)){
              _this.$refs.dlTableExt.tableData.splice(_this.$refs.dlTableExt.tableData.findIndex(item => item.id === n.id), 1)
            }
          });
        _this.waitingCount-=selApplyIds.length;
        });
        },
        cancelDialog(){
        this.dl.show = false;
        },
        createContract(){
          let idArray = this.$refs.dlTableExt.getIdArray();
          let ids = idArray.join();
          let param = qs.stringify({ids:ids});
          this.axios.post(this.lib.config.host.contract+'/contractmgt/contract/editPageSource',param).
          then(res=>{
            let result = res.data;
            if(result.success){
              this.contract = result.resultMap.contract;
              this.purContractTypeList = result.resultMap.purContractTypeList;
              this.editor.sync = true;
            }else{
              this.showMsg('error',result.message);
            }
          }).catch(e=>{
            this.showMsg('error',e);
          });
        },
        setBtListText(count){
          this.btListText = '待签清单('+count+')';
        },
        createSuc(contractId,contractModel){
          this.editor.sync = false;
          this.cancelDialog();
          if(contractModel==1){
            this.waitingCount = 0;
            this.$refs.dlTableExt.tableData = [];
            this.$refs.tableExt.refreshTable();
          }else{
            this.contentEditor.sync=true;
            this.editId=contractId;
          }
        },
        contentEditorClose(){
          this.editId = '';
          this.contentEditor.sync = false;
        },
        editContentSuc(){
           this.contentEditor.sync = false;
           this.editId = '';
           this.waitingCount = 0;
           this.$refs.tableExt.refreshTable();
        },
        contentEditorClose(){
          this.editId = '';
          this.contentEditor.sync = false;
        },
        saveContent(){
          this.$refs.contentEditor.save();
        }
    }
  }
</script>
<style>
.contractapply-waiting{
  margin-left: 16px;
}

</style>
